package com.zpark.exception;

import com.zpark.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.zpark.controller")
public class GlobalExceptionHandler {
    // 处理校验失败异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidateException(MethodArgumentNotValidException e) {
        // 获取BindingResult
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>(8);
        // 将校验错误字段和错误信息提取到map中
        bindingResult.getFieldErrors().forEach(item -> errorMap.put(item.getField(),item.getDefaultMessage()));
        return R.error(400,"数据校验出错").put("error", errorMap);
    }

    // 处理其他异常
    @ExceptionHandler(Exception.class)
    public R handleOtherException(Exception e) {
        return R.error(e.getMessage());
    }
}
